/**
 * Created by yangfan on 2016/8/31.
 */
define(['config/appregister',"../../services/httpServices","business/services/commentService",
    "domReady","_","i18n","business/services/components","business/services/constant"],function(app,httpService,commentServices,domReady,_,i18n,components,constant){
   app.filter("bracket",function(){
       return function (input) {
           if(typeof input == "undefined" ||typeof input =="null")return;
               return "("+input + ")"
       }
   });
    app.directive("refreshValue",function(){
            return {
                require:"ngModel",
                link:function(scope,element,attrs,ctrl){
                    scope.$watch("draw.size",function(newValue,oldValue){
                        if(newValue !=""){
                                ctrl.$setViewValue(scope.draw);
                        }
                    })

                }
            }
    }).directive("comComment",function($rootScope,$state){
            return {
                templateUrl:"app/business/library/directives/templates/uiComment.html",
                controller:function($scope,$element,$attrs,$q){
                    $scope.textarea = "";
                    //点击加载更多
                    var pageNo = 1;
                },
                scope:{
                    conf:"=commentConf"
                },
                link:function(scope,element,attrs){
                    scope.i18n = i18n;
                    scope.emoji = constant.QQface.emojis;
                    scope.face = constant.QQface.face;
                    scope.isShowCurSec = [];
                    scope.isReplyTopComment = [];
                    scope.isReplySecComment = [];
                    scope.isReplySecTopComment = false;
                    scope.isShowStar =false;
                    scope.userInfo = $rootScope.userLoginInfo.data;
                    if(scope.conf.showStar && angular.isBoolean(scope.conf.showStar)){
                        scope.isShowStar = scope.conf.showStar;
                    }
                    var conf = scope.conf;
                    var pageNo = 1;
                    var screenWidth = window.screen.availWidth;
                    var screenHeight =  window.screen.availHeight;
                    scope.replies = "";

                    //getTopComment
                    function getTopComment(setpage){
                        if( typeof setpage == "number"){
                            pageNo = setpage;
                        }
                        var req = {
                            type:"GET",
                            base:conf.base,
                            uri:conf.uri.getTopComment,
                            data:{
                                id:conf.id,
                                pageSize:5,
                                all:false,
                                pageNo:pageNo
                            }
                        };
                        //通过setpage 来判断是否是点击更多
                        commentServices.commonHttpServices(req).success(function(response){
                            if(!response.data){return};
                            scope.$apply(function(){
                                if(setpage && scope.list){
                                    var arr =  scope.list.concat(response.data.list);
                                    scope.list = arr;
                                    }else{
                                        scope.list = response.data.list;
                                        scope.num = response.data.Pagination.totalCount;
                                    }
                                scope.isShowTopPagination = pageNo >= Math.ceil(response.data.Pagination.totalCount/response.data.Pagination.pageSize)?false : true ;
                                });
                            })
                    }

                    //publish comment
                    function publish(){
                        if(!$rootScope.userLoginInfo.logged){
                            $state.go('login');
                            return ;
                        }
                        var  req = {
                            type:"POST",
                            base:conf.base,
                            uri:conf.uri.publish,
                            data:{
                                id:conf.id,
                                content:scope.textarea,
                                //authStatus:1
                            }

                        };

                        if(scope.isShowStar){
                            req.data.evalCount = scope.curEvalCount;
                        }
                        commentServices.commonHttpServices(req).success(function(response){
                             scope.$apply(function(){
                                scope.textarea = "";
                                     alert(response.msg)
                            })
                        })
                    };
                    function addReply(item){
                        var  req = {
                            type:"POST",
                            base:conf.base,
                            uri:conf.uri.reply,
                            data:{}
                        };

                        if(scope.isShowStar){
                            req.data ={
                                id:conf.id,
                                commentId:item.evaluateId,
                                content:scope.replies
                            }
                        }else {
                            req.data={
                                id:conf.id,
                                commentId:item.commentId,
                                content:scope.replies
                            }
                        }
                        commentServices.commonHttpServices(req).success(function(response){});
                    };
                    //获取二级评论
                    function getAllCommentsByTopId(item,setpage,isAll){
                        var pageNo = 1;
                        if( typeof setpage == "number"){
                            pageNo = setpage;
                        }
                        var req = {
                            type:"GET",
                            base:conf.base,
                            uri:conf.uri.getSecComment,
                            data:{
                                pageSize:2,
                                all:false,
                                pageNo:pageNo,
                                topId:item.commentId
                            }
                        };
                        if(isAll == "all"){
                            req.data.all = true;
                        };
                        //通过setpage 来判断是否是点击更多
                        commentServices.commonHttpServices(req).success(function(response){
                            if(!response.data){return};
                            scope.$apply(function(){
                                if(setpage ||isAll){
                                    var arr =  scope.secComment.concat(response.data.list);
                                    scope.secComment = arr;
                                }else{
                                    scope.secComment = response.data.list;
                                }
                                scope.isShowSecPagination = pageNo>= Math.ceil(response.data.Pagination.totalCount/response.data.Pagination.pageSize)?false : true ;
                            });
                        });

                    };
                    getTopComment();

                    //点击加载更多
                    //var pageNo = 1;
                    scope.loadMoreComment = function(){
                        pageNo++;
                        getTopComment(pageNo);
                    };

                    //发表评论
                    scope.publish = function(){
                    scope.textarea = document.getElementById("f-publish").value;
                        publish();
                    };

                    //回复评论
                    scope.addReply = function(item){
                        addReply(item);
                        scope.onchange.clearTextarea();
                    };

                    //得到二级评论
                    scope.checkComment = function(item,index){
                        scope.currentItem1 = item;
                        var html = document.getElementById("comment-opacity-view");
                        $("#comment-opacity-view").addClass("comment-opacity-view").css("top",0).css("left",0)
                            .css("display","block")
                            .css("height",screenHeight)
                            .css("width",screenWidth);

                        var screenWidth2 = window.screen.availWidth;
                        scope.childCommentStyle = {
                            left:(screenWidth2-690)/2 +"px",
                            top:"20px"
                        };
                        scope.isShowCurSec = [];
                        scope.isShowCurSec[index] = true;
                        getAllCommentsByTopId(item);
                    };
                    //得到更多二级评论
                    var secPage = 2;
                    scope.checkMoreSecComment = function(item){
                        getAllCommentsByTopId(item,secPage);
                        secPage++;
                    };
                    scope.checkAllSecComment = function(item){
                        var isAll = "all";
                        getAllCommentsByTopId(item,secPage,isAll);
                    };

                    scope.closeSecComment = function(){
                        secPage = 2;
                        $("#comment-opacity-view").removeClass("comment-opacity-view")
                            .css("display","none");
                        scope.isShowCurSec = [];

                    };
                    scope.onchange = {
                        changeReplyTopComment:function(index){
                            if(typeof  scope.currentTopRepIndex == "number"&&scope.currentTopRepIndex == index){
                                scope.isReplyTopComment[index] = false;
                                scope.currentTopRepIndex =null;
                            }else{
                                scope.currentTopRepIndex = index;
                                scope.isReplyTopComment = [];
                                scope.isReplyTopComment[index] =true;
                            }
                        },
                        changeReplySecTopComment:function(){
                            scope.isReplySecTopComment = !scope.isReplySecTopComment;
                        },
                        changeReplySecComment:function(index){
                            if(typeof  scope.currentSecRepIndex == "number"&&scope.currentSecRepIndex == index){
                                scope.isReplySecComment[index] = !scope.isReplySecComment[index];
                            }else{
                                scope.currentSecRepIndex = index;
                                scope.isReplySecTopComment = false;
                                scope.isReplySecComment = [];
                                scope.isReplySecComment[index] =true;
                            }
                        },
                        clearTextarea:function(){
                            scope.replies = "";
                            scope.isReplyTopComment = [];
                            scope.isReplySecComment = [];
                            scope.isReplySecTopComment = false;
                        }
                    };
                    scope.isShowEmoji = false;
                    var insertAtCaret = function(textDom,textFeildValue){
                     //   var textObj = $(this).get(0);
                        var textObj = textDom;
                        if(document.all && textObj.createTextRange && textObj.caretPos){
                            var caretPos=textObj.caretPos;
                            caretPos.text = caretPos.text.charAt(caretPos.text.length-1) == '' ?
                            textFeildValue+'' : textFeildValue;
                        } else if(textObj.setSelectionRange){
                            var rangeStart=textObj.selectionStart;
                            var rangeEnd=textObj.selectionEnd;
                            var tempStr1=textObj.value.substring(0,rangeStart);
                            var tempStr2=textObj.value.substring(rangeEnd);
                            textObj.value=tempStr1+textFeildValue+tempStr2;
                            textObj.focus();
                            var len=textFeildValue.length;
                            textObj.setSelectionRange(rangeStart+len,rangeStart+len);
                            textObj.blur();
                        }else{
                            textObj.value+=textFeildValue;
                        }
                    }
                    scope.emoji = {
                        onchange:function(){
                         scope.isShowEmoji  = !scope.isShowEmoji;
                        },
                        addEmoji :function(event,item,type){
                              if(type &&type == "publish"){
                                  var textObj =   document.getElementById('f-publish');
                                  insertAtCaret(textObj, item)

                                //  scope.textarea = scope.textarea + item;
                        }

                    }



                }
                }}
        }).directive("getPraises",function(){
        return {
            scope:{
                item:"=getItem",
                conf:"=getConf"
            },
            require:"^comComment",
            template:'<a  ng-bind="i18n.support" ng-click="support(item)"></a><a href="" ng-bind="praiseCount |bracket"></a>' +
            '<a ng-bind="i18n.oppose" ng-click="oppose(item)"></a> <a href="" ng-bind="stampCount |bracket"></a>',
            link:function(scope,element,attrs){
                var conf = scope.conf;
                scope.i18n = i18n;
                scope.praiseCount = 0;
                scope.stampCount = 0;
                scope.isShowStar =false;
                if(scope.conf.showStar && angular.isBoolean(scope.conf.showStar)){
                    scope.isShowStar = scope.conf.showStar;
                };
              if(scope.item){
                  scope.praiseCount = scope.item.praiseCount;
                  scope.stampCount = scope.item.stampCount;
              };
                function addPraise(item,type){
                    var commentId = item.commentId;
                    var  req = {
                        type:"POST",
                        base:conf.base,
                        uri:conf.uri.praise,
                        data:{}
                    };

                    if(scope.isShowStar){
                        req.data ={
                            evalCommentId:item.evalCommentId,
                            praiseType:type
                        }
                    }else {
                        req.data={
                            commentId:item.commentId,
                            type:type
                        }
                    };
                    commentServices.commonHttpServices(req).success(function(data){
                        scope.$apply(function(){
                            if(data.code&&data.code==110){
                                return;
                            }
                            if(type ==1){
                                    scope.praiseCount+=1;
                            }
                            if(type ==2){
                                scope.stampCount+=1;
                            }
                        })
                    });
                }
                scope.support = function(item){
                    var  type =1;
                    addPraise(item,type);
                    };
                scope.oppose = function(item){
                    var  type =2;
                    addPraise(item,type);
                };
                }
                }
    }).
        factory("commentHttpServices",function($q){

        if(localStorage.fileId){
            var fileId = localStorage.fileId;
            };
               return {
                   getComment:function(requstion){
                        var deferred = $q.defer();
                  var req ={
                type:"GET",
                uri:requstion.uri,
                data:{
                    fileId:requstion.fileId,
                    pageNo:1,
                    pageSize:10,
                    topId:requstion.topId
                }
            };
            httpService.getComment(req).success(function(response){
                if(!response.data)return;
                deferred.resolve(response.data);

            }).error(function(response){
                deferred.reject(response.data);
            });
                       return deferred.promise;
                   },
                   addPraise :function(type,commentId,fileId){
                     var deferred = $q.defer();
                     var  req = {
                type:"POST",
                uri:"addPraise",
                data:{
                    commentId:commentId,
                    type:type,
                    userId:1
                }
            };
            httpService.addPraise(req).success(function(response){
                if(!response)return;
                deferred.resolve(response);
            }).error(function(response){
                deferred.reject(response);
            });
             return deferred.promise;
        },
                   publish:function(textarea){
                       var deferred = $q.defer();
                       var  req = {
                           type:"POST",
                           uri:"add",
                           data:{
                               fileId:fileId,
                               userId:1,
                               content:textarea,
                               authStatus:1
                           }
                       };
                       httpService.addComment(req).success(function(response){
                           deferred.resolve(response);
                       }).error(function(){
                           deferred.reject(response);
                       })
                       return deferred.promise;
                   },
                   getMoreComment:function(pageNo) {
                       var deferred = $q.defer();
                     var req ={
                     type:"GET",
                     uri:"getTopCommentsByFileId",
                     data:{
                        fileId:fileId,
                        pageNo:pageNo,
                        pageSize:5,
                        all:false
                    }
                };
                httpService.getComment(req).success(function(response){
                    if(!response.data)return;
                    deferred.resolve(response);
                }).error(function(){
                    deferred.reject(response);
                });
                       return deferred.promise;
            }
               }
    })
});
